<template>
  <div class="content">
    <div class="pageSearchView">
      <SearchForm v-model="searchParam" :fields="searchFields" :handleSearch="handleSearch" />
    </div>

    <div class="pageTableView">
      <div class="pageTableMenuView">
        <div class="pageTableTitle">
          列表信息 <el-icon><house-icon /></el-icon>
        </div>
        <div class="pageTableButView">
          <el-button :icon="Plus" @click="handleAdd">新建</el-button>
          <!-- 添加列按钮 -->
          <el-button :icon="Plus" @click="showAddColumnDialog = true" type="primary">表头列配置</el-button>
        </div>
      </div>
      <!-- 表格 -->
      <el-table class="pageTableClass" :data="paginatedData" height="calc(100vh - 350px)" :loading="isLoading">
        <el-table-column label="序号" align="center">
          <template #default="scope">
            {{ (paginationParams.current - 1) * paginationParams.pageSize + scope.$index + 1 }}
          </template>
        </el-table-column>
        <el-table-column prop="name" label="周期名称" align="center" />
        <el-table-column prop="code" label="周期编码" align="center">
          <template #default="scope">
            {{ scope.row.code }}
          </template>
        </el-table-column>
        <el-table-column prop="materialType" label="周期有效期" align="center" width="300">
          <template #default="scope">
            {{ scope.row.cycleStartDate + '-' + scope.row.cycleEndDate }}
          </template>
        </el-table-column>

        <!-- 动态列渲染 -->
        <el-table-column v-for="col in columns" :key="col.key" :prop="col.key" :label="col.label" align="center" />
        <el-table-column label="操作" align="center" fixed="right" width="180">
          <template #default="scope">
            <el-button @click="handleEdit(scope.row)" size="small" plain text :icon="Edit">编辑</el-button>
            <el-button @click="handleDel(scope.row)" type="danger" size="small" plain text :icon="Delete">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagePagination">
        <el-pagination background v-model:current-page="paginationParams.current"
          v-model:page-size="paginationParams.pageSize" layout="total, sizes, prev, pager, next" :total="pageTotal"
          @size-change="handleSizeChange" @current-change="handleCurrentChange" />
      </div>
    </div>
    <!-- 弹窗表单22 -->
    <el-dialog v-model="showCrud" :title="crudTitle" width=500>
      <el-form :model="formData" label-width="130px" ref="ruleFormRef" :rules="rules">
        <el-row>

          <el-form-item label="周期名称" required prop="name">
            <el-input v-model="formData.name" placeholder="请输入周期名称" style="width: 300px" />
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="周期编码" required prop="code">
            <el-input v-model="formData.code" placeholder="请输入周期编码" style="width: 300px" />
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="周期有效期" required prop="cycleStartDate">
            <el-date-picker v-model="formData.cycleStartDate" type="datetimerange" style="width:300px"
              start-placeholder="开始日期" end-placeholder="结束日期" format="YYYY-MM-DD " value-format="YYYY-MM-DD HH:mm:ss" />
          </el-form-item>
        </el-row>

        <el-form-item label="周期类型" prop="triggerCycleType">

          <el-radio-group v-model="formData.triggerCycleType">
            <el-radio :value="1">日</el-radio>
            <el-radio :value="2">周</el-radio>
            <el-radio :value="3">月</el-radio>
          </el-radio-group>
        </el-form-item>



        <el-form-item label="周期间隔" prop="invokeFrequency" v-if="[1, 2, 3].includes(formData.triggerCycleType)">
          <el-input-number v-model="formData.invokeFrequency" :min="0" style="width:300px" />
        </el-form-item>
        <el-form-item label="提前生成天数" prop="advanceDate" v-if="[1, 2, 3].includes(formData.triggerCycleType)">
          <el-input-number v-model="formData.advanceDate" :min="0" style="width:300px" />
        </el-form-item>
        <el-form-item label="执行开始周期" prop="invokeBegin" v-if="[2].includes(formData.triggerCycleType)">
          <el-select multiple v-model="formData.invokeBegin" placeholder="请选择周期" clearable style="width: 300px">
            <el-option v-for="(item, index) of week" :key="index" :label="item.value" :value="item.label" />
          </el-select>
        </el-form-item>
        <el-form-item label="执行开始日期" prop="invokeBegin" v-if="[3].includes(formData.triggerCycleType)">
          <el-select multiple v-model="formData.invokeBegin" placeholder="请选择日期" clearable style="width: 300px">
            <el-option v-for="n in 31" :key="n" :label="`${n}号`" :value="n" />
          </el-select>
        </el-form-item>
        <el-form-item label="执行开始时刻" prop="triggerTime" v-if="[1, 2, 3].includes(formData.triggerCycleType)">
          <el-time-picker v-model="formData.triggerTime" value-format="YYYY-MM-DD HH:mm:ss" arrow-control
            placeholder="请选择和执行开始时刻" style="width:300px" />

        </el-form-item>
        <!-- 动态字段在弹窗中渲染 -->
        <el-col :span="12" v-for="col in columns" :key="col.key">
          <el-form-item :label="col.label" :prop="col.key">
            <el-input v-model="formData[col.key]" :placeholder="`请输入${col.label}`" style="width: 300px" />
          </el-form-item>
        </el-col>
      </el-form>
      <template v-slot:footer>
        <div class="dialog-footer">
          <el-button @click="showCrud = false">取消</el-button>
          <el-button type="primary" @click="handleSave">保存</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 动态添加列的对话框 -->
    <el-dialog v-model="showAddColumnDialog" title="管理列信息">
      <!-- 表格增删改查 -->
      <el-button :icon="Plus" @click="showAddColumnDialog2 = true; columnDialogTitle = '新建'" type="primary"
        style="margin-bottom: 20px;">新建列</el-button>
      <el-table :data="columns">
        <el-table-column prop="label" label="列名称" align="center" />
        <el-table-column prop="key" label="列编码" align="center" />
        <el-table-column prop="visible" label="是否展示" align="center">
          <template #default="scope">
            {{ scope.row.visible ? "是" : '否' }}
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center">
          <template #default="scope">
            <el-button @click="editColumn(scope.row, scope.$index)" size="small" icon="Edit">编辑</el-button>
            <el-button @click="deleteColumn(scope.$index)" size="small" type="danger" icon="Delete">删除</el-button>
          </template>
        </el-table-column>
      </el-table>



      <template #footer>
        <el-button @click="showAddColumnDialog = false">关闭</el-button>
      </template>
    </el-dialog>
    <!-- 动态添加列的对话框 -->
    <el-dialog v-model="showAddColumnDialog2" :title="columnDialogTitle">
      <el-form>
        <el-form-item label="列名称">
          <el-input v-model="newColumn.label" placeholder="请输入列名称" />
        </el-form-item>
        <el-form-item label="列Key">
          <el-input v-model="newColumn.key" placeholder="请输入列Key" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showAddColumnDialog2 = false">取消</el-button>
        <el-button type="primary" @click="addColumn">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>
<script lang="ts" setup>
import SearchForm from '@/components/SearchForm.vue';
import { useMaterialata } from '@/hooks/device/cycleManagement';
import { Delete, Edit, Plus } from '@element-plus/icons-vue';
import { ElMessageBox } from 'element-plus'; // 假设使用 Element Plus
import { onMounted,computed, ref, watch } from 'vue';

const {
  searchParam,
  paginationParams,
  pageTotal,
  paginatedData,
  searchFields,
  handleSearch,
  handleSizeChange,
  handleCurrentChange,
  addmateriaL,
  deletemateriaL,
  isLoading,
  ruleFormRef,
  rules,
  formData,
  week,
  restForm,
  moldType,
  fetchPageData
} = useMaterialata();

// 动态列和新列的数据
const columns = ref([
  { label: '自定义列1', key: 'column1', visible: true },
  { label: '自定义列2', key: 'column2', visible: true },
  // 可添加更多默认列
]);
const showAddColumnDialog = ref(false);
const showAddColumnDialog2 = ref(false);
const columnDialogTitle = ref("")
const columnIndexNumber = ref(0)
const newColumn = ref({
  label: '',
  key: '',
  visible: true,
});
onMounted(() => {
  moldType.value=2
  fetchPageData({...searchParam.value,type:2})


});
// 新建列
const addColumn = () => {
  if (newColumn.value.label && newColumn.value.key) {

    if (columnDialogTitle.value === "新建") {
      columns.value.push({ ...newColumn.value });
      newColumn.value = { label: '', key: '', visible: true };
      showAddColumnDialog2.value = false
    }
    else {
      columns.value[columnIndexNumber.value].key = newColumn.value.key
      columns.value[columnIndexNumber.value].label = newColumn.value.label
      columns.value[columnIndexNumber.value].visible = newColumn.value.visible
      showAddColumnDialog2.value = false
    }

  }
};

// 编辑列
const editColumn = (row: any, index: number) => {

  columnIndexNumber.value = index
  columnDialogTitle.value = "编辑"
  showAddColumnDialog2.value = true
  newColumn.value.label = row.label
  newColumn.value.key = row.key
};

// 删除列
const deleteColumn = (index: number) => {
  columns.value.splice(index, 1);
};

const isEdit = ref(false);
const showCrud = ref(false);
const crudTitle = computed(() => {
  return isEdit.value ? '编辑' : '新建';
});


// 新建记录
const handleAdd = () => {
  isEdit.value = false;
  formData.value = { ...restForm.value,    type:2,};
  showCrud.value = true;
};

// 编辑记录
const handleEdit = (row: any) => {

  isEdit.value = true;
  formData.value = {
    ...row,
    type:2,
    cycleStartDate: [row.cycleStartDate, row.cycleStartDate],
    invokeBegin: JSON.parse(row.invokeBegin),
 
  };

  showCrud.value = true;
};

// 删除记录
const handleDel = (row: any) => {
  ElMessageBox.confirm('确定删除该条记录吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    await deletemateriaL(row.id);
  }).catch(() => {
  });
};


// 保存记录
const handleSave = async () => {
  await addmateriaL(formData.value, (() => {
    showCrud.value = false;
  }));
};

watch(() => formData.value.triggerCycleType, (newVal) => {
  if (!isEdit.value) { // 只有在新建模式下才清空
    switch (newVal) {
      case 1:
        formData.value.invokeFrequency = 0;
        formData.value.advanceDate = 0;
        formData.value.triggerTime = '';
        break;
      case 2:
        formData.value.invokeFrequency = 0;
        formData.value.advanceDate = 0;
        formData.value.invokeBegin = [];
        formData.value.triggerTime = '';
        break;
      case 3:
        formData.value.invokeFrequency = 0;
        formData.value.advanceDate = 0;
        formData.value.invokeBegin = [];
        formData.value.triggerTime = '';
        break;
      default:
        break;
    }
  }
});;

</script>

<style scoped></style>
